import axios from 'axios'

import { AxiosReqTy, AxiosConfigTy } from '../../types/common'

const service: any = axios.create()

// 请求拦截
service.interceptors.request.use(
    (request: AxiosReqTy) => {
        request.headers['AUTHORIZE_TOKEN'] = 'token' //设置token
        request.headers['X-GW-AccessKey'] = "XGWAccessKey"; //配置网关
        /* download file*/
        if (request.isDownLoadFile) {
            request.responseType = 'blob'
        }
        /* upload file*/
        if (request.isUploadFile) {
            request.headers['Content-Type'] = 'multipart/form-data'
        }
    },
    (err: any) => {
        Promise.reject(err)
    }
)

// 响应拦截
service.interceptors.response.use(
    (res: any) => {
        // debugger
        const { data, status } = res
        //更新token保持登录状态
        if (status == '200') {
            return data
        } else {
            // ElMessage({
            //     message: data.msg,
            //     type: 'error',
            //     duration: 2 * 1000
            // })
        }
    },
    (err: any) => {
        return Promise.reject(err)
    }
)

export function request({
    url,
    data,
    method,
    isParams,
    bfLoading,
    afHLoading,
    isUploadFile,
    isDownLoadFile,
    baseURL,
    timeout,
    isAlertErrorMsg = true
}: AxiosConfigTy): any {
    return service({
        url: url,
        method: method ?? 'get',
        data: data ?? {},
        isParams: isParams ?? false,
        bfLoading: bfLoading ?? false,
        afHLoading: afHLoading ?? true,
        isUploadFile: isUploadFile ?? false,
        isDownLoadFile: isDownLoadFile ?? false,
        isAlertErrorMsg: isAlertErrorMsg,
        baseURL: baseURL ?? apiBase.baseURL,
        timeout: timeout ?? 15000
    })
}